import { ref, onMounted, onUnmounted, onDeactivated, onActivated } from 'vue'
import BScroll from '@better-scroll/core'
import ObserveDOM from '@better-scroll/observe-dom'
BScroll.use(ObserveDOM)

function useScroll(wrapperRef, options = {}, emit) {
  const scroll = ref(null)
  onMounted(() => {
    scroll.value = new BScroll(wrapperRef.value, {
      click: true,
      scrollX: false,
      scrollY: true,
      bounce: true,
      probeType: 0,
      observeDOM: true,
      ...options
    })
    scroll.value.on('scroll', pos => {
      emit('scroll', -pos.y)
    })
  })

  onUnmounted(() => {
    scroll.value.destroy()
  })

  onActivated(() => {
    scroll.value.enable()
    scroll.value.refresh()
  })

  onDeactivated(() => {
    scroll.value.disable()
  })

  return {
    scroll
  }
}

export default useScroll
